import { Login, userInfo } from '@/api/user.js'
import router, { powerRoutes, constantRoutes } from '@/router'
export default {
  namespaced: true,
  state: {
    token: '',
    // 用户信息
    userInfo: {},
    // 用户密码
    password: ''
  },
  mutations: {
    SETTOKEN(state, value) {
      state.token = value
    },
    // 修改用户信息
    setUserInfo(state, value) {
      state.userInfo = value
    },
    // token失效，删除token，删除用户信息
    delTokenInfo(state) {
      state.token = ''
      state.userInfo = {}
    }
  },
  actions: {
    async toLogin({ commit }, value) {
      // ctx:{state,commit}
      const res = await Login(value)
      console.log(res)

      // localStorage.setItem('userToken', res.data.data.token)

      commit('SETTOKEN', res.data.data.token)
    },
    // 用户信息
    async toGetUserInfo({ commit }) {
      const res = await userInfo()
      console.log(res)
      const res1 = res.data.data
      commit('setUserInfo', res1)
      const spuer = ['companysList', 'userList', 'questionList', 'subjectList']
      const manger = ['companysList', 'userList', 'questionList']
      const teacher = ['userList', 'questionList']
      const student = ['userList']
      let arr = []
      if (res1.role_id === 1) {
        arr = powerRoutes.filter((item) => {
          return spuer.includes(item.meta.code)
        })
      } else if (res1.role_id === 2) {
        arr = powerRoutes.filter((item) => {
          return manger.includes(item.meta.code)
        })
      } else if (res1.role_id === 3) {
        arr = powerRoutes.filter((item) => {
          return teacher.includes(item.meta.code)
        })
      } else if (res1.role_id === 4) {
        arr = powerRoutes.filter((item) => {
          return student.includes(item.meta.code)
        })
      }
      console.log(arr)
      arr.push({ path: '*', redirect: '/404', hidden: true })
      router.addRoutes(arr)
      router.options.routes = [...constantRoutes, ...arr]
    }
  }
}
